package com.example.git_app_yanshi;


import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

import com.example.git_app_yanshi.R;

public class NoteEditorActivity extends AppCompatActivity {
    private EditText titleEditText, contentEditText;
    private boolean isEditMode;
    private int noteIndex;
    private NoteDatabaseHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_note_editor);

        dbHelper = new NoteDatabaseHelper(this);

        titleEditText = findViewById(R.id.title);
        contentEditText = findViewById(R.id.content);
        Button saveButton = findViewById(R.id.save_button);
        Button backButton = findViewById(R.id.back_button);

        isEditMode = getIntent().getBooleanExtra("isEditMode", false);
        if (isEditMode) {
            noteIndex = getIntent().getIntExtra("noteIndex", -1);
            titleEditText.setText(getIntent().getStringExtra("title"));
            contentEditText.setText(getIntent().getStringExtra("content"));
        }

        saveButton.setOnClickListener(v -> saveNote());
        backButton.setOnClickListener(v -> finish());
    }

    private void saveNote() {
        String title = titleEditText.getText().toString().trim();
        String content = contentEditText.getText().toString().trim();

        if (TextUtils.isEmpty(title)) {
            Toast.makeText(this, "标题不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(NoteDatabaseHelper.COLUMN_TITLE, title);
        values.put(NoteDatabaseHelper.COLUMN_CONTENT, content);

        if (isEditMode) {
            // 更新笔记
            db.update(
                    NoteDatabaseHelper.TABLE_NAME,
                    values,
                    null,
                    null
            );
        } else {
            // 插入新笔记
            db.insert(
                    NoteDatabaseHelper.TABLE_NAME,
                    null,
                    values
            );
        }

        // 返回结果给 NotesListActivity
        Intent resultIntent = new Intent();
        setResult(RESULT_OK, resultIntent);
        finish();
    }
}
